package com.wuliu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wuliu.auto.JSONAuthentication;

import com.wuliu.entity.ExCar;
import com.wuliu.entity.ExOrder;
import com.wuliu.entity.ExUser;
import com.wuliu.mapper.ExCarMapper;
import com.wuliu.mapper.ExLxMapper;
import com.wuliu.mapper.ExOrderMapper;
import com.wuliu.mapper.ExUserMapper;
import com.wuliu.response.Result;
import com.wuliu.utils.BaiDuApiUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuliu
 * @since 2022-03-05
 */
@RestController
@RequestMapping("/ex-order")
public class ExOrderController extends JSONAuthentication {
    @Autowired
    ExOrderMapper exOrderMapper;
    @Autowired
    ExUserMapper exUserMapper;
    @Autowired
    ExCarMapper exCarMapper;
    @Autowired
    ExLxMapper exLxMapper;
    @ApiOperation("添加订单")
    @PostMapping("/add")
    public void addOrder(HttpServletRequest request, HttpServletResponse response, @RequestParam("userId") int userId, @RequestParam("startPoint") String startPoint, @RequestParam("endPoint") String endPoint, @RequestParam("shouhuoId") int shouhuoId,@RequestParam("fahuoId") int fahuoId,@RequestParam("wight") float wight,@RequestParam("prName") String prName) throws Exception{
        ExOrder exOrder=new ExOrder();
        exOrder.setUserId(userId);
        exOrder.setStartPoint(startPoint);
        exOrder.setEndPoint(endPoint);
        exOrder.setFahuoId(fahuoId);
        exOrder.setShouhuoId(shouhuoId);
        exOrder.setWight(wight);
        exOrder.setPrNmae(prName);
        String start =new BaiDuApiUtils().getCoordinate(exOrder.getStartPoint());
        String end=new BaiDuApiUtils().getCoordinate(exOrder.getEndPoint());
        //根据经纬度计算出距离
        Double juli=new BaiDuApiUtils().getDistance(start,end);
        //根据距离 重量查询出需要多少钱
        Double price =juli/40000*exOrder.getWight();
        if(price<15){
            price=15.0;
        }
        exOrder.setPrice(price);
        if(exOrderMapper.insert(exOrder)>0){
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        }else{
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "删除订单")
    @PostMapping("/del")
    public void delUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id ) throws Exception{
        int i=exOrderMapper.deleteById(id);
        if(i>0){
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "修改运送物品重量并修改价格")
    @PostMapping("/updPhone")
    public void updPhone(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id,@RequestParam("wight") float  wight)throws Exception{
        ExOrder exOrder=exOrderMapper.selectById(id);
       exOrder.setWight(wight);
        String start =new BaiDuApiUtils().getCoordinate(exOrder.getStartPoint());
        String end=new BaiDuApiUtils().getCoordinate(exOrder.getEndPoint());
        //根据经纬度计算出距离
        Double juli=new BaiDuApiUtils().getDistance(start,end);
        //根据距离 重量查询出需要多少钱
        Double price =juli/40000*exOrder.getWight();
        if(price<15){
            price=15.0;
        }
        exOrder.setPrice(price);
        if(exOrderMapper.updateById(exOrder)>0){
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "给已支付的订单配发货车")
    @PostMapping("/peisong")
    public void peisong(HttpServletRequest request, HttpServletResponse response, @RequestParam("carId") int carId,@RequestParam("id") int id)throws Exception{
        ExOrder exOrder=exOrderMapper.selectById(id);
        exOrder.setCarId(carId);
        if(exOrderMapper.updateById(exOrder)>0){
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "查询订单通过下单人id")
    @PostMapping("/findByUserId")
    public void findByUserId(HttpServletRequest request, HttpServletResponse response,@RequestParam("userId") int   userId,@RequestParam("size") int size,@RequestParam ("current") int current)throws  Exception{
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("user_id",userId);
        Page<ExOrder> shUserPage=new Page<>(current,size);
        Page<ExOrder> shUserPages=exOrderMapper.selectPage(shUserPage,wrapper);
        List<ExOrder> records = shUserPages.getRecords();
        int total=exOrderMapper.selectCount(wrapper);
        for(ExOrder a:records){
            a.setExUser(exUserMapper.selectById(a.getUserId()));
            if(a.getCarId()!=0){
                a.setExCar(exCarMapper.selectById(a.getCarId()));
            }
        }
        if(records.size()>0){
            Result ok = Result.ok().data("userList",records).data("total",total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error().message("没有订单");
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "查询未支付的订单")
    @PostMapping("/findNoPay")
    public void findNoPay(HttpServletRequest request, HttpServletResponse response,@RequestParam("size") int size,@RequestParam ("current") int current)throws  Exception{
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("status","未支付");
        Page<ExOrder> shUserPage=new Page<>(current,size);
        Page<ExOrder> shUserPages=exOrderMapper.selectPage(shUserPage,wrapper);
        List<ExOrder> records = shUserPages.getRecords();
        int total=exOrderMapper.selectCount(wrapper);
        for(ExOrder a:records){
            a.setExUser(exUserMapper.selectById(a.getUserId()));
            if(a.getCarId()!=0){
                a.setExCar(exCarMapper.selectById(a.getCarId()));
            }
        }
        if(records.size()>0){
            Result ok = Result.ok().data("userList",records).data("total",total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error().message("没有订单");
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "查询正在运送的订单")
    @PostMapping("/findYunSong")
    public void findYunSong(HttpServletRequest request, HttpServletResponse response,@RequestParam("size") int size,@RequestParam ("current") int current)throws  Exception{
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("status","正在运送");
        Page<ExOrder> shUserPage=new Page<>(current,size);
        Page<ExOrder> shUserPages=exOrderMapper.selectPage(shUserPage,wrapper);
        List<ExOrder> records = shUserPages.getRecords();
        int total=exOrderMapper.selectCount(wrapper);
        for(ExOrder a:records){
            a.setExUser(exUserMapper.selectById(a.getUserId()));
            if(a.getCarId()!=0){
                a.setExCar(exCarMapper.selectById(a.getCarId()));
            }
        }
        if(records.size()>0){
            Result ok = Result.ok().data("userList",records).data("total",total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error().message("没有订单");
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "查询已送达的订单")
    @PostMapping("/findSongda")
    public void findSongda(HttpServletRequest request, HttpServletResponse response,@RequestParam("size") int size,@RequestParam ("current") int current)throws  Exception{
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("status","已送达");
        Page<ExOrder> shUserPage=new Page<>(current,size);
        Page<ExOrder> shUserPages=exOrderMapper.selectPage(shUserPage,wrapper);
        List<ExOrder> records = shUserPages.getRecords();
        int total=exOrderMapper.selectCount(wrapper);
        for(ExOrder a:records){
            a.setExUser(exUserMapper.selectById(a.getUserId()));
            if(a.getCarId()!=0){
                a.setExCar(exCarMapper.selectById(a.getCarId()));
            }
        }
        if(records.size()>0){
            Result ok = Result.ok().data("userList",records).data("total",total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error().message("没有订单");
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "查询所有订单")
    @PostMapping("/findAllOrder")
    public void findAllOrder(HttpServletRequest request, HttpServletResponse response,@RequestParam("size") int size,@RequestParam ("current") int current)throws  Exception{
        Page<ExOrder> shUserPage=new Page<>(current,size);
        Page<ExOrder> shUserPages=exOrderMapper.selectPage(shUserPage,null);
        List<ExOrder> records = shUserPages.getRecords();
        int total=exOrderMapper.selectCount(null);
        for(ExOrder a:records){
            a.setExUser(exUserMapper.selectById(a.getUserId()));
            if(a.getCarId()!=0){
                a.setExCar(exCarMapper.selectById(a.getCarId()));
            }
        }
        if(records.size()>0){
            Result ok = Result.ok().data("userList",records).data("total",total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error().message("没有订单");
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "查询订单通过寄送物品名")
    @PostMapping("/findByPrName")
    public void findByPrName(HttpServletRequest request, HttpServletResponse response,@RequestParam("size") int size,@RequestParam ("current") int current,@RequestParam("prName")String prName)throws  Exception{
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.like("pr_name",prName);
        Page<ExOrder> shUserPage=new Page<>(current,size);
        Page<ExOrder> shUserPages=exOrderMapper.selectPage(shUserPage,wrapper);
        List<ExOrder> records = shUserPages.getRecords();
        int total=exOrderMapper.selectCount(wrapper);
        for(ExOrder a:records){
            a.setExUser(exUserMapper.selectById(a.getUserId()));
            if(a.getCarId()!=0){
                a.setExCar(exCarMapper.selectById(a.getCarId()));
            }
        }
        if(records.size()>0){
            Result ok = Result.ok().data("userList",records).data("total",total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error().message("没有订单");
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "查询订单通过订单id并支付")
    @PostMapping("/payOrder")
    public void payOrder(HttpServletRequest request, HttpServletResponse response,@RequestParam("id") int  id)throws  Exception{
        ExOrder exOrder = exOrderMapper.selectById(id);
        ExUser exUser=exUserMapper.selectById(exOrder.getUserId());
        Double balance=exUser.getBalance();
        Double price=exOrder.getPrice();
        if(balance-price<0){
            Result error = Result.error().message("余额不足,请充值");
            this.WriteJSON(request, response, error);
        }else{
            exUser.setBalance(balance-price);
            QueryWrapper wrapper=new QueryWrapper();
            wrapper.eq("status","待分配");
            List<ExCar> exCars=exCarMapper.selectList(wrapper);
            List<Integer> carId=new ArrayList<>();
            for(ExCar a :exCars){
                carId.add(a.getId());
            }
            Random random=new Random();
            int huoche=random.nextInt(carId.size());
            exOrder.setCarId(huoche);
            exOrder.setStatus("运送中");
            ExCar exCar = exCarMapper.selectById(huoche);
            exCar.setStatus("运输中");
            if(exUserMapper.updateById(exUser)>0&&exOrderMapper.updateById(exOrder)>0&&exCarMapper.updateById(exCar)>0){
                Result ok = Result.ok().message("支付成功");
                this.WriteJSON(request, response, ok);

            } else {
                Result error = Result.error().message("支付失败");
                this.WriteJSON(request, response, error);
            }
        }

    }
    @ApiOperation(value = "查询订单通订单id")
    @PostMapping("/findByOrderId")
    public void findByOrderId(HttpServletRequest request, HttpServletResponse response,@RequestParam("id") int   id)throws  Exception{
        ExOrder exOrder=exOrderMapper.selectById(id);
        exOrder.setExUser(exUserMapper.selectById(exOrder.getUserId()));
            if(exOrder.getCarId()!=0){
                exOrder.setExCar(exCarMapper.selectById(exOrder.getCarId()));
            }
        if(exOrder!=null){
            Result ok = Result.ok().data("userList",exOrder);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error().message("没有订单");
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "货车到达")
    @PostMapping("/daoda")
    public void daoda(HttpServletRequest request, HttpServletResponse response,@RequestParam("id") int id)throws  Exception{
        ExOrder exOrder=exOrderMapper.selectById(id);
        exOrder.setStatus("已到达");
        int carId=exOrder.getCarId();
        ExCar exCar = exCarMapper.selectById(carId);
        exCar.setStatus("已到达");
        if(exOrderMapper.updateById(exOrder)>0&&exCarMapper.updateById(exCar)>0){
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "收货接口")
    @PostMapping("/shouhuo")
    public void shouhuo(HttpServletRequest request, HttpServletResponse response,@RequestParam("id") int id)throws  Exception{
        ExOrder exOrder=exOrderMapper.selectById(id);
        exOrder.setStatus("已签收");
        int carId=exOrder.getCarId();
        ExCar exCar = exCarMapper.selectById(carId);
        exCar.setStatus("待分配");
        if(exOrderMapper.updateById(exOrder)>0){
            Result ok = Result.ok().data("userList",exOrder);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
}

